package com.wilmer.user.service;

import com.wilmer.common.constant.Constants;
import com.wilmer.common.core.domain.AjaxResult;
import com.wilmer.common.core.domain.entity.SysUser;
import com.wilmer.common.core.domain.model.LoginUser;
import com.wilmer.common.exception.base.BaseException;
import com.wilmer.common.utils.MessageUtils;
import com.wilmer.common.utils.sign.Md5Utils;
import com.wilmer.framework.manager.AsyncManager;
import com.wilmer.framework.manager.factory.AsyncFactory;
import com.wilmer.framework.web.service.TokenService;
import com.wilmer.framework.web.smsConfig.SmsCodeAuthenticationToken;
import com.wilmer.system.mapper.SysUserMapper;
import com.wilmer.user.domain.WeChatLogin;
import com.wilmer.user.mapper.WeChatLoginMapper;
import com.wilmer.utils.GetWxPhoneUtil;
import com.wilmer.utils.OpenIdUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class WeChatLoginService {

    @Resource
    private OpenIdUtil openIdUtil;
    @Resource
    private GetWxPhoneUtil getWxPhoneUtil;
    @Resource
    private WeChatLoginMapper weChatLoginMapper;
    @Resource
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private SysUserMapper userMapper;

    public String creatToken(String mobile) {

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager
                    .authenticate(new SmsCodeAuthenticationToken(mobile));
        } catch (Exception e) {

            AsyncManager.me().execute(AsyncFactory.recordLogininfor(mobile, Constants.LOGIN_FAIL, e.getMessage()));
            throw new BaseException(e.getMessage());

        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(mobile, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        AjaxResult ajax = AjaxResult.success();

        // 生成token
        String token = tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);

        return token;
    }

    private void creatWechatUser(String openId, String phone) {
        SysUser weChatUser = new SysUser();

        weChatUser.setOpenId(openId);

        weChatUser.setUserName(phone);

        weChatUser.setNickName(phone);

        weChatUser.setPhonenumber(phone);

        weChatUser.setPassword(Md5Utils.hash(phone));

        weChatUser.setSex("1");

        weChatUser.setStatus("0");

        weChatUser.setDelFlag("0");

        weChatUser.setRemark("小程序用户");

        int i = userMapper.insertUser(weChatUser);

    }

    public String getWechatUser(WeChatLogin weChatLogin) {

        String openId = openIdUtil.getOpenId(weChatLogin.getLoginCode()).getOpenid();
        String phone = getWxPhoneUtil.getPhone(weChatLogin.getPhoneCode());

        SysUser user = weChatLoginMapper.getWechatUserByOpenId(openId);

        System.out.println(user+"------------");

        if (user != null) {
            //获取手机号
            String mobile = user.getPhonenumber();
            //登录
            String s = creatToken(mobile);
            return s;
        } else {
            //注册后登录
            creatWechatUser(openId, phone);
            //获取手机号

            return creatToken(phone);


        }


    }

}
